package com.jdk.demo.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class Client {

	public static void main(String[] args) throws Exception {
        AsynchronousSocketChannel client = AsynchronousSocketChannel.open();
        client.connect(new InetSocketAddress("127.0.0.1", 8013), null, new CompletionHandler<Void, Object>() {
			@Override
			public void completed(Void result, Object attachment) {
				ByteBuffer buffer = ByteBuffer.allocate(100);
		        client.read(buffer, null, new CompletionHandler<Integer, Void>() {
		            @Override
		            public void completed(Integer result, Void attachment) {
		            	buffer.flip();
		            	byte[] bytes = new byte[buffer.remaining()];
		            	buffer.get(bytes);
		                System.out.println("client received: " + new String(bytes));
		            }
		            @Override
		            public void failed(Throwable exc, Void attachment) {
		                exc.printStackTrace();
		                try {
		                    client.close();
		                } catch (IOException e) {
		                    e.printStackTrace();
		                }

		            }
		        });
			}
			@Override
			public void failed(Throwable exc, Object attachment) {

			}
        });
        Thread.sleep(1000000);
    }

}
